#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 9
#define MAX_ARRAY_SIZE 1024

int* result = (int*)malloc(MAX_ARRAY_SIZE*sizeof(int));
    printf("\n INIT: %x \n", result);
    memset(result, 0, MAX_ARRAY_SIZE);
    int* PtrToResult = result;

void swap ( int* a, int* b ) {
    if (a == b) return;
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int* Permutation ( int* PtrToResult, int* result, int L[], int Left, int Right ) {
    int i;
    // int* PtrToResult = result;
    if ( Left == Right ) {
        printf("XX %x ", PtrToResult);
        for ( i = 0; i <= Right; i++ ) {
            printf("%d ",L[i]);
            *PtrToResult = L[i];
            PtrToResult++;
        }
        printf("%x \n", PtrToResult);
    } else {
        for ( i = Left; i <= Right; i++ ) {
            swap(&L[Left],&L[i]);
            int* cur = Permutation(PtrToResult,result,L,Left+1,Right);
            // if (cur == result)
            // result = cur;
            printf("LOOP %x %x \n", cur, result);
            swap(&L[i],&L[Left]);
        }
    }
    return PtrToResult;
}

int main () {
    int N, L[MAXN], i, cnt = 0;
    scanf("%d",&N);
    for ( i = 0; i < N; i++ ) L[i] = i + 1;
    // int* result = (int*)malloc(MAX_ARRAY_SIZE*sizeof(int));
    // printf("\n INIT: %x \n", result);
    // memset(result, 0, MAX_ARRAY_SIZE);
    // int* PtrToResult = result;
    // 
    int* final = Permutation(PtrToResult,result,L,0,N-1);
    printf("\nFINAL: %x %d \n", result, final- result);
    
    while(PtrToResult) {
        printf("%d ",*PtrToResult);
        PtrToResult++;
        cnt++;
        if ( cnt == N ) {
            printf("\n");
            cnt = 0;
        }
        if (*PtrToResult == 0) break;
    }
    free(result);
    return 0;
}